//
//  UserAccountViewModel.swift
//  ydy_weibo
//
//  Created by 杨德勇 on 16/7/16.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

import UIKit
import AFNetworking
//这个类设计目的是减少controller的代码量，处理业务逻辑在这个类里面进行。
class UserAccountViewModel: NSObject {
    //新建一个userAccount属性
    var account : UserAccount?
    
    //新建一个用户是否登陆的属性
    var userLogin:Bool {
        return account?.access_token != nil
    }
    //新建一个属性记录token，方便后续使用
    var token : String?{
        return account?.access_token
    }
    //新建一个属性保存用户名字
    var userName: String? {
        return account?.name
    }
    //新建一个属性保存用户头像url
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    
    
    override init() {
        account = UserAccount.loadAccount()
    }
    
    //获取用户token
    func loadAccessToken(code:String,finished:(error : NSError? )->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":client_id,
                          "client_secret":client_secret,
                          "grant_type" :"authorization_code",
                          "code":code,
                          "redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        AFN.POST(urlString, parameters: parameters, success: { (nil, result) in
            //            print(success)
            if let dict = result as? [String:AnyObject]{
                //取到数据，开始字典转模型
                let account = UserAccount(dict:dict)
                self.loadUserInfo(account, finished: finished)
            }
        }) { (nil, error) in
            
        }
    }
    //
    //MARK:-
    //MARK:获取用户信息
    private func loadUserInfo(account:UserAccount,finished:(error : NSError? )->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, success: { (_, result) in
            if let dict = result as? [String:AnyObject]{
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                account.saveAccount()
            }
            //闭包在这里执行
            finished(error: nil)
            
        }) { (_, error) in
            print(error)
            finished(error: error)
        }
    }
    
}



